package com.authine.cloudpivot.web.api.advice;

import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.controller.CustAccessLogService;
import com.authine.cloudpivot.ext.dto.CustAccessLog;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.util.AuthUtils;
import com.authine.cloudpivot.web.api.view.runtime.QueryDataVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 * @Author hxd
 * @Date 2021/11/12 17:53
 * @Description 列表查询
 **/
@Slf4j
@Aspect
@Component
public class GetListAspect {
    @Autowired
    private CustAccessLogService custAccessLogService;

    /**
     * Pointcut 切入点
     *
     */
    @Pointcut("execution(* com.authine.cloudpivot.web.api.controller.runtime.QueryRuntimeController.list(*))")
    public void listAspect(){}

    /**
     * 环绕通知
     */
//    @Around(value = "webLog()")
    public Object arround(ProceedingJoinPoint pjp) {
        try {
            log.info("1、Around：方法环绕开始.....");
            Object o =  pjp.proceed();
            log.info("3、Around：方法环绕结束，结果是 :" + o);
            return o;
        } catch (Throwable e) {
            log.error(pjp.getSignature() + " 出现异常： ", e);
        }
        return null;
    }

    /**
     * 方法执行前
     */
    @Before(value = "listAspect()")
    public void before(JoinPoint joinPoint){
//        log.info("2、Before：方法执行开始...");
//        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
//        // 记录下请求内容
//        log.info("URL : " + request.getRequestURL().toString());
//        log.info("HTTP_METHOD : " + request.getMethod());
//        log.info("IP : " + request.getRemoteAddr());
//        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//        log.info("=======================ARGS : " + Arrays.toString(joinPoint.getArgs()));

        try {

            CustAccessLog log = CustAccessLog.builder().ip(request.getRemoteAddr())
                    .method(joinPoint.getSignature().getName())
                    .reqTime(new Date())
                    .userId(AuthUtils.getUserId())
                    .schemaCode(getSchemaCode(joinPoint.getArgs()))
                    .build();

            custAccessLogService.addLog(log);
        } catch (Exception e) {
            log.info("list 日志添加失败:{}", e);
        }

    }


    private String getSchemaCode(Object[] args){
        if (args != null) {
            QueryDataVO arg = (QueryDataVO) args[0];
            return arg.getSchemaCode();
        }

       return null;
    }

    /**
     * 方法执行结束，不管是抛出异常或者正常退出都会执行
     */
//    @After(value = "listAspect()")
    public void after(JoinPoint joinPoint){


    }

    /**
     * 方法执行结束，增强处理
     */
//    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret){
        // 处理完请求，返回内容

    }

    /**
     * 后置异常通知
     */
//    @AfterThrowing(value = "webLog()")
    public void throwss(JoinPoint joinPoint){

    }
}
